package chapter04.sync;

public class ABCTest2 {
    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify(1,5);
        new Thread(()->{waitNotify.print("a",1,2);},"t1").start();
        new Thread(()->{waitNotify.print("b",2,3);},"t2").start();
        new Thread(()->{waitNotify.print("c",3,1);},"t3").start();
    }
}
class WaitNotify{
    // 开始打印顺序
    private int flag;

    // 循环次数
    private int loopNumber;

    public WaitNotify(int flag, int loopNumber) {
        this.flag = flag;
        this.loopNumber = loopNumber;
    }

    public void print(String str,int waitFlag,int nextFlag){
        for(int i=1;i<=loopNumber;i++){
            synchronized (this){
                while (flag!=waitFlag){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(str);
                flag=nextFlag;
                this.notifyAll();
            }
        }
    }
}
